using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Teamwish.Domain.Models;
using Domain;
using Teamwish.Domain.ViewModels;
using Teamwish.Domain.Models.Enums;
using System.Text;
using System.Data.Entity.Infrastructure;
using Teamwish.Domain.IBLL;
using Teamwish.Domain.Common;
using Teamwish.WebUI.Filters;

namespace Teamwish.WebUI.Areas.Admin.Controllers
{
    [AdminAuthorize(Roles = "管理员")]
    public class UserinfoController : Controller
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private EfDbContext db = DIFactory.Resolve<EfDbContext>();
        /// <summary>
        /// 用户列表页
        /// </summary>
        /// <param name="search"></param>
        /// <param name="state"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ActionResult List(SearchInfo search, string state, int page = 1, int pageSize = 10)
        {
            var rows = db.Userinfo.AsNoTracking().AsQueryable();

            //条件查询拼接
            if (!string.IsNullOrWhiteSpace(search.Key))
            {
                rows = rows.Where(p => p.Username.Contains(search.Key.Trim()));
            }
            if (search.BeginDt!=null)
            {
                rows = rows.Where(p => p.CreateDate>=search.BeginDt);
            }
            if (search.EndDt != null)
            {
                rows = rows.Where(p => p.CreateDate < search.EndDt);
            }
            if (!string.IsNullOrWhiteSpace(search.State))
            {
                //Flag flag = (Flag)Enum.Parse(typeof(Flag), search.State);
                rows = rows.Where(p => p.State == Flag.正常);
            }

            //符合过滤条件的数量
            int count = rows.Count();
            rows = rows.OrderByDescending(p => p.Id).Skip((page - 1) * pageSize).Take(pageSize);

            //强类型输出，viewdata补充
            UserInfoListPage result = new UserInfoListPage
            {
                List = rows.ToList(),
                PageIndex = page,
                TotalCount = count,
                PageSize = pageSize,
                Key = search.Key,
                BeginDt = search.BeginDt,
                EndDt = search.EndDt
            };
            return View(result);
        }

        /// <summary>
        /// 用户创建页面
        /// </summary>
        /// <param name="rowitem"></param>
        /// <param name="selectedCourses"></param>
        /// <returns></returns>
        public ActionResult Create()
        {
            var rowitem = new Userinfo();
            return View(rowitem);
        }

        /// <summary>
        /// 处理用户创建页面
        /// </summary>
        /// <param name="rowitem"></param>
        /// <param name="selectedCourses"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Username,Password,Email,Telephone,Address,Postcode,CreateDate,State,Remark,Role")]Userinfo rowitem, string[] selectedCourses)
        {
            if (rowitem.Username.Trim()=="Admin")
            {
                ModelState.AddModelError("Username", "用户名已存在");
            }
            if (db.Userinfo.Any(p=>p.Username== rowitem.Username.Trim()))
            {
                ModelState.AddModelError("Username","用户名已存在");
            }
            if (ModelState.IsValid)
            {
                rowitem.Password = Teamwish.Utilities.Md5Helper.MD5(rowitem.Password, 32);
                db.Userinfo.Add(rowitem);
                db.SaveChanges();
                TempData["Msg"] = "保存成功!";
                return RedirectToAction(nameof(Create));
            }
            TempData["Msg"] = "保存失败!";
            return View(rowitem);
        }
        /// <summary>
        /// 用户编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Userinfo rowitem = db.Userinfo.Find(id);
            if (rowitem == null)
            {
                return HttpNotFound();
            }

            return View(rowitem);
        }

        /// <summary>
        /// 用户数据保存编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="selectedCourses"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int? id,string password, string[] selectedCourses)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var rowitem = db.Userinfo.Find(id);

            if (TryUpdateModel(rowitem, "", new string[] {"Email", "Telephone", "Address", "Postcode", "CreateDate", "State", "Remark" , "Role" }))
            {
                try
                {
                    if (!string.IsNullOrWhiteSpace(password))
                    {
                        rowitem.Password = Teamwish.Utilities.Md5Helper.MD5(password.Trim(), 32);

                    }
                    db.SaveChanges();
                    TempData["Msg"] = "保存成功!";
                    return RedirectToAction(nameof(Edit), new { id = rowitem.Id });
                }
                catch (DbUpdateException /* ex */)
                {
                    ModelState.AddModelError("", "无法保存！");
                }

            }
            
            TempData["Msg"] = "保存失败!";
            return View(rowitem);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                Userinfo rowitem = db.Userinfo.Find(id);
                db.Userinfo.Remove(rowitem);
                db.SaveChanges();
                return Content("Ok");
            }
            catch
            {
                return Content("Fail");
            }
        }
        [HttpPost]
        public ActionResult DeleteMany(string[] ids)
        {

            try
            {
                foreach (var id in ids)
                {
                    Userinfo obj = db.Userinfo.Find(int.Parse(id));
                    db.Userinfo.Remove(obj);
                }
                db.SaveChanges();  
                
                //userinfoBLL.DeleteMany(ids);
                return Content("Ok");
            }
            catch
            {
                return Content("Fail");
            }

        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                //db.Dispose();
            }
            base.Dispose(disposing);
        }

    }
}


